from duckserver.models import User, Follow
from duckserver.models import Grouprelation
from duckserver.models import Community
from duckserver.models import Work
from duckserver.service.admin import report
from django.conf import settings
import datetime
import time
from duckserver.service.user import getUserInfo
from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger

# 创建圈子
from duckserver.service.duckPowerEgg import costEgg


def createGroup(userid, groupname, description, backgroundimage, announcement, reason):
    response = {'groupid': 0, 'ok': 0, 'msg': ''}
    if costEgg(userid, 50):
        g = Community.objects.filter(groupname=groupname)
        if len(g) != 0:
            response['msg'] = "圈子已存在"
            return response

        # 新建圈子
        user = User.objects.get(userid=userid)
        group = Community(userid=user, groupname=groupname,
                          status=2, description=description, announcement=announcement)
        group.save()
        group.backgroundimage = backgroundimage
        group.save()
        groupid = group.groupid

        # 提交管理员审核
        report(3, groupid, reason)

        # 修改user圈子数量
        user = User.objects.get(userid=userid)
        user.groupNum = user.groupNum + 1
        user.save()
        # 修改grouprelation表对应关系
        grouprelation = Grouprelation(userid=user, groupid=group)
        grouprelation.save()

        response['groupid'] = groupid
        response["ok"] = 1
    else:
        response['msg'] = "鸭蛋不足"
    return response


# 获取圈子信息
def getGroupMessage(groupid, userid):
    response = {'groupname': '', 'creatorid': '', 'username': '', 'createtime': '', 'status': 0, 'description': '',
                'backgroundimage': '', 'membernum': 0, 'groupworknum': 0, 'ismember': True, 'ok': 0, 'msg': ''}
    group = Community.objects.get(groupid=groupid)
    user = User.objects.get(userid=userid)

    response['groupid'] = group.groupid
    response['groupname'] = group.groupname
    response['creatorid'] = group.userid.userid
    response['creatorname'] = group.userid.username
    # 判断是否关注圈主
    follow = Follow.objects.filter(userid=group.userid, follower=user)
    if len(follow) == 0:
        response['creatorFollow'] = False
    else:
        response['creatorFollow'] = True

    response['creatorHeadImg'] = settings.ROOT_URL + group.userid.headImage.url
    response['createtime'] = group.createtime
    response['status'] = group.status
    response['description'] = group.description
    response['briefDescription'] = "%.10s..." % group.description
    response['announcement'] = group.announcement   # 公告
    response['backgroundimage'] = settings.ROOT_URL + group.backgroundimage.url
    # 获取成员数量
    members = Grouprelation.objects.filter(groupid=groupid)
    response['membernum'] = len(members)
    # 获取作品数量
    works = Work.objects.filter(groupid=groupid)
    response['groupworknum'] = len(works)
    # 判断是否加入圈子
    grouprelation = Grouprelation.objects.filter(groupid=group, userid=user)
    if(len(grouprelation) == 0):
        response['ismember'] = False
    else:
        response['ismember'] = True

    response["ok"] = 1
    return response

# 获取圈子列表


def getGroupList(userid, page, num=5):
    num = int(num)
    response = {'data': [], 'ok': 0, 'msg': ''}
    groups = Grouprelation.objects.filter(userid=userid, groupid__status=0).exclude(groupid=1)
    if len(groups) == 0:
        response['msg'] = "该用户没有加入任何圈子"
        return response
    paginator = Paginator(groups, num)
    group_page = paginator.page(page)   # 分页 从1开始
    response['max'] = paginator.count   # 总条数

    groupList = []
    for group in group_page:
        group = group.groupid
        groupid = group.groupid
        groupList.append(getGroupMessage(groupid, userid))

    response['groupList'] = groupList
    response["ok"] = 1
    return response

# 加入圈子


def joinGroup(groupid, userid):
    response = {'grouprelationid': 0, 'ok': 0, 'msg': ''}

    if int(groupid) == 1:
        response['msg'] = "该圈子无法加入"
        return response

    group = Community.objects.get(groupid=groupid)
    user = User.objects.get(userid=userid)
    if group.status == 1:
        response['msg'] = "圈子因违规已经封闭"
        return response
    if group.status == 2:
        response['msg'] = "管理员正在审核，请稍后再尝试"
        return response

    # 查询是否已加入
    gg = Grouprelation.objects.filter(userid=user, groupid=group)
    if len(gg) > 0:
        response['msg'] = "请勿重复加入"
        return response

    # 修改user圈子数量
    user = User.objects.get(userid=userid)
    user.groupNum = user.groupNum + 1
    user.save()
    # 修改grouprelation表对应关系
    grouprelation = Grouprelation(userid=user, groupid=group)
    grouprelation.save()

    response["grouprelationid"] = grouprelation.relationid
    response["ok"] = 1
    return response


# 退出圈子
def exitGroup(groupid, userid):
    response = {'groupid': 0, 'ok': 0, 'msg': ''}
    group = Community.objects.get(groupid=groupid)
    response['groupid'] = group.groupid
    # 修改user圈子数量
    user = User.objects.get(userid=userid)
    user.groupNum = user.groupNum - 1
    user.save()
    # 删除圈子关系
    grouprelation = Grouprelation.objects.filter(userid=user, groupid=group)[0]
    grouprelation.delete()

    response['ok'] = 1
    return response


# 获取圈子成员列表
def getGroupMember(groupid, userid, num, page):
    page = int(page)
    num = int(num)
    response = {'ok': 0, 'msg': ''}
    group = Community.objects.get(groupid=groupid)
    user = User.objects.get(userid=userid)

    response['groupid'] = group.groupid

    relations = Grouprelation.objects.filter(
        groupid=group).order_by("relationid")
    paginator = Paginator(relations, num)
    relationss_page = paginator.page(page)   # 分页 从1开始
    response['max'] = paginator.count

    userList = []
    for relation in relationss_page:
        userList.append(getUserInfo(relation.userid_id, userid))

    response['userList'] = userList
    response['ok'] = 1
    return response

# 时间格式转换


def timestamp2string(timeStamp):
    try:
        d = datetime.datetime.fromtimestamp(int(timeStamp))
        str1 = d.strftime("%Y-%m-%d %H:%M:%S")
        # 2015-08-28 16:43:37'
        return str1
    except Exception as e:
        print(e)
        return ''
